package ltd.cheers.mall.controller.mall;

import lombok.extern.slf4j.Slf4j;
import ltd.cheers.mall.common.CheersMallException;
import ltd.cheers.mall.common.CheersMallOrderStatusEnum;
import ltd.cheers.mall.common.Constants;
import ltd.cheers.mall.common.ServiceResultEnum;
import ltd.cheers.mall.controller.vo.CheersMallOrderDetailVO;
import ltd.cheers.mall.controller.vo.CheersMallOrderItemVO;
import ltd.cheers.mall.controller.vo.CheersMallShoppingCartItemVO;
import ltd.cheers.mall.controller.vo.CheersMallUserVO;
import ltd.cheers.mall.entity.CheersMallOrder;
import ltd.cheers.mall.service.CheersMallOrderService;
import ltd.cheers.mall.service.CheersMallShoppingCartService;
import ltd.cheers.mall.util.PageQueryUtil;
import ltd.cheers.mall.util.Result;
import ltd.cheers.mall.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author: LiHuanYang
 * @date: 2020/3/28 下午 09:58
 */
@Slf4j
@Controller
public class OrderController {

    @Resource
    private CheersMallShoppingCartService cheersMallShoppingCartService;
    @Resource
    private CheersMallOrderService cheersMallOrderService;

    @GetMapping("/orders/{orderNo}")
    public String orderDetailPage(HttpServletRequest request, @PathVariable("orderNo") String orderNo, HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        CheersMallOrderDetailVO orderDetailVO = cheersMallOrderService.getOrderDetailByOrderNo(orderNo, user.getUserId());
        if (orderDetailVO == null) {
            return "error/error_5xx";
        }
        request.setAttribute("orderDetailVO", orderDetailVO);
        return "mall/order-detail";
    }

    @GetMapping("/orders")
    public String orderListPage(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        params.put("userId", user.getUserId());
        if (StringUtils.isEmpty(params.get("page"))) {
            params.put("page", 1);
        }
        params.put("limit", Constants.ORDER_SEARCH_PAGE_LIMIT);
        //封装我的订单数据
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        request.setAttribute("orderPageResult", cheersMallOrderService.getMyOrders(pageUtil));
        request.setAttribute("path", "orders");
        return "mall/my-orders";
    }

    @GetMapping("/saveOrder")
    public String saveOrder(HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        List<CheersMallShoppingCartItemVO> myShoppingCartItems = cheersMallShoppingCartService.getMyShoppingCartItems(user.getUserId());
        if (StringUtils.isEmpty(user.getAddress().trim())) {
            //无收货地址
            CheersMallException.fail(ServiceResultEnum.NULL_ADDRESS_ERROR.getResult());
        }
        if (CollectionUtils.isEmpty(myShoppingCartItems)) {
            //购物车中无数据则跳转至错误页
            CheersMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
        }
        //保存订单并返回订单号
        String saveOrderResult = cheersMallOrderService.saveOrder(user, myShoppingCartItems);
        //跳转到订单详情页
        return "redirect:/orders/" + saveOrderResult;
    }

    @PutMapping("/orders/{orderNo}/cancel")
    @ResponseBody
    public Result cancelOrder(@PathVariable("orderNo") String orderNo, HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        String cancelOrderResult = cheersMallOrderService.cancelOrder(orderNo, user.getUserId());
        if (ServiceResultEnum.SUCCESS.getResult().equals(cancelOrderResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(cancelOrderResult);
        }
    }

    @PutMapping("/orders/{orderNo}/finish")
    @ResponseBody
    public Result finishOrder(@PathVariable("orderNo") String orderNo, HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        String finishOrderResult = cheersMallOrderService.finishOrder(orderNo, user.getUserId());
        if (ServiceResultEnum.SUCCESS.getResult().equals(finishOrderResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(finishOrderResult);
        }
    }

    @GetMapping("/selectPayType")
    public String selectPayType(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        CheersMallOrder cheersMallOrder = cheersMallOrderService.getCheersMallOrderByOrderNo(orderNo);
        if (user.getUserId()==cheersMallOrder.getUserId()&&cheersMallOrder.getOrderStatus()== CheersMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()){
            log.debug("通过用户状态验证！");
            request.setAttribute("orderNo", orderNo);
            request.setAttribute("totalPrice", cheersMallOrder.getTotalPrice());
            return "mall/pay-select";
        }
        return "error/error_5xx";
    }

    @GetMapping("/payPage")
    public String payOrder(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession, @RequestParam("payType") int payType, RedirectAttributes attributes) {
        CheersMallUserVO user = (CheersMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        CheersMallOrder cheersMallOrder = cheersMallOrderService.getCheersMallOrderByOrderNo(orderNo);
        List<CheersMallOrderItemVO> orderItems = cheersMallOrderService.getOrderItems(cheersMallOrder.getOrderId());
        String itemString = "";
        if (!CollectionUtils.isEmpty(orderItems)) {
            for (int i = 0; i < orderItems.size(); i++) {
                itemString += orderItems.get(i).getGoodsName() + " x " + orderItems.get(i).getGoodsCount() +" ";
            }
        }
        log.debug("订单商品详情 "+itemString);
        // 判断订单userId 验证是否是当前userId下的订单，否则报错 by thy 20200301 已添加验证是否同一用户
        // 判断订单状态 by thy 20200301 已添加验证状态为待支付 '0'
        if (user.getUserId() == cheersMallOrder.getUserId()&&cheersMallOrder.getOrderStatus()== CheersMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()&&cheersMallOrder.getPayStatus()==CheersMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
            log.debug("通过用户状态验证！");
            request.setAttribute("orderNo", orderNo);
            request.setAttribute("totalPrice", cheersMallOrder.getTotalPrice());
            if (payType == 1) {
                //payType == 1为支付宝支付 重定向到支付宝沙箱接口controller 进行支付
                //使用RedirectAttributes 拼key和value 自动帮拼到url上 不会出现中文乱码
                attributes.addAttribute("orderNo", orderNo);
                attributes.addAttribute("totalPrice", cheersMallOrder.getTotalPrice());
                attributes.addAttribute("itemString", itemString);
                return "redirect:/alipay/goAlipay";
            } else {
                return "mall/wxpay";
            }
        }
            return "error/error_5xx";
        }

    @GetMapping("/paySuccess")
    @ResponseBody
    public Result paySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("payType") int payType) {
        String payResult = cheersMallOrderService.paySuccess(orderNo, payType);
        if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(payResult);
        }
    }

}